package com.suke.czx.modules.incentivegrant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.suke.czx.common.utils.FieldConstant;
import com.suke.czx.common.utils.NumUtil;
import com.suke.czx.common.utils.R;
import com.suke.czx.modules.incentive.entity.Incentive;
import com.suke.czx.modules.incentive.entity.IncentiveGenerateBo;
import com.suke.czx.modules.incentive.service.IncentiveService;
import com.suke.czx.modules.incentivegrant.entity.IncentiveGrant;
import com.suke.czx.modules.incentivegrant.mapper.IncentiveGrantMapper;
import com.suke.czx.modules.incentivegrant.service.IncentiveGrantService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 应用模块名称: 绩效发放
 * 代码描述: 绩效发放业务层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2022/08/12 17:26:16
 */
@Slf4j
@Service
@AllArgsConstructor
public class IncentiveGrantServiceImpl implements IncentiveGrantService {

    private final IncentiveService incentiveService;

    private final IncentiveGrantMapper incentiveGrantMapper;

    /**
     * 初始化绩效发放
     * @param projectId 项目id
     * @param year 年份
     * @param version 版本
     * @return VO
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(rollbackFor = Exception.class)
    public R initial(Long projectId, String year, Integer version) {
        // 结果集
        List<IncentiveGrant> grantList = new ArrayList<>();
        // 1.查询项目及合同信息
        IncentiveGrant info = incentiveGrantMapper.getInfo(projectId);
        // 2.初始化绩效
        IncentiveGenerateBo incentiveGenerateBo = new IncentiveGenerateBo();
        incentiveGenerateBo.setProjectId(projectId);
        incentiveGenerateBo.setYear(year);
        incentiveGenerateBo.setVersion(version);
        R r = incentiveService.initial(incentiveGenerateBo);
        // 3.如果初始化绩效成功查询绩效分配
        if (r.get(FieldConstant.CODE) != null && NumUtil.null2IntegerZero(StrUtil.toString(r.get(FieldConstant.CODE))) == 0) {
            List<Incentive> incentiveList = (List<Incentive>) r.get(FieldConstant.DATA);
            Optional.ofNullable(incentiveList).orElse(Lists.newArrayList()).forEach(j ->
                    Optional.ofNullable(j.getChildren()).orElse(Lists.newArrayList()).forEach(u ->
                            grantList.add(generateIncentiveGrant(info, j.getJob2(), j.getPerformanceConfigId(), u.getUserId(),
                                    u.getName(), u.getTotalReward(), u.getGenerateTime(), u.getNote()))));
            return R.ok().setData(grantList);
        } else {
            return r;
        }
    }

    /**
     * 绩效发放
     * @param incentiveGrant 绩效发放实体
     * @param userId 用户id
     * @return VO
     */
    public R grant(IncentiveGrant incentiveGrant, Long userId) {
        incentiveGrant.setGrantTime(new Date());
        incentiveGrant.setCreator(userId);
        incentiveGrant.setCreateTime(new Date());
        incentiveGrantMapper.insertIncentiveGrant(incentiveGrant);
        return R.ok();
    }

    /**
     * 更新绩效发放
     * @param incentiveGrant 绩效发放实体
     * @return VO
     */
    public R update(IncentiveGrant incentiveGrant) {
        incentiveGrantMapper.updateIncentiveGrant(incentiveGrant);
        return R.ok();
    }

    /**
     * 删除绩效发放
     * @param incentiveGrantId 绩效发放id
     * @param userId 用户id
     * @return VO
     */
    public R delete(Long incentiveGrantId, Long userId) {
        incentiveGrantMapper.updateDelIncentiveGrant(incentiveGrantId, userId);
        return R.ok();
    }

    /**
     * 生成绩效发放记录
     * @param info 项目信息
     * @param job2 组别
     * @param performanceConfigId 绩效参数id
     * @param userId 员工id
     * @param name 员工姓名
     * @param amount 金额
     * @param generateTime 绩效分配时间
     * @param note 备注
     * @return 绩效发放实体
     */
    private IncentiveGrant generateIncentiveGrant(IncentiveGrant info, Integer job2, Long performanceConfigId, Long userId,
                                                  String name, BigDecimal amount, Date generateTime, String note) {
        // 生成一级分配记录
        IncentiveGrant allocation = buildIncentiveGrant(info, job2, performanceConfigId, userId, name, amount, generateTime, note);
        // 设置二级发放记录
        allocation.setChildren(incentiveGrantMapper.getIncentiveGrant(info.getProjectId(), job2, performanceConfigId));
        // 返回结果
        return allocation;
    }

    /**
     * 构建一级绩效分配记录
     * @param info 项目及合同信息
     * @param job2 组别
     * @param performanceConfigId 绩效参数id
     * @param userId 员工id
     * @param name 员工姓名
     * @param amount 绩效金额
     * @param generateTime 绩效分配时间
     * @param note 备注
     */
    private IncentiveGrant buildIncentiveGrant(IncentiveGrant info, Integer job2, Long performanceConfigId, Long userId,
                                               String name, BigDecimal amount, Date generateTime, String note) {
        IncentiveGrant grant = new IncentiveGrant();
        grant.setProjectId(info.getProjectId());
        grant.setProjectName(info.getProjectName());
        grant.setJob2(job2);
        grant.setPerformanceConfigId(performanceConfigId);
        grant.setUserId(userId);
        grant.setName(name);
        grant.setAmount(amount);
        grant.setGrantTime(generateTime);
        grant.setNote(note);
        return grant;
    }

}